package cn.com.git.workflow.config.freemarker.tag.sys;

import cn.com.git.common.model.Dict;
import cn.com.git.common.model.DictBuilder;
import cn.com.git.common.model.DictMapper;
import com.google.common.collect.Lists;
import freemarker.core.Environment;
import freemarker.ext.beans.BeansWrapper;
import freemarker.ext.beans.BeansWrapperBuilder;
import freemarker.template.*;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class SysDictTag implements TemplateDirectiveModel {

    private List<DictMapper> mappers = Lists.newArrayList();

    public SysDictTag() {
        this.initMapper();
    }

    /**
     * 初始化mapper
     */
    private void initMapper(){
        this.mappers.add(getSysResourceTypeDict());
    }

    @Override
    public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody templateDirectiveBody) throws TemplateException, IOException {
        String namespace = map.get("namespace").toString();
        List<DictMapper> dictMappers = mappers.stream().filter(s->s.getNamespace().equals(namespace)).collect(Collectors.toList());
        DictBuilder dictBuilder = dictMappers.get(0).getBuilder();
        List<Dict> dicts = dictBuilder.build();
        environment.setVariable("noteDicts", getBeansWrapper().wrap(dicts));
        templateDirectiveBody.render(environment.getOut());
    }

    private static BeansWrapper getBeansWrapper(){
        BeansWrapper beansWrapper =
                new BeansWrapperBuilder(Configuration.VERSION_2_3_27).build();
        return beansWrapper;
    }
    /**
     * 系统资源类型
     * @return
     */
    private DictMapper getSysResourceTypeDict(){
        return new DictMapper("workflow_type", () -> {
            List<Dict> dicts = Arrays.asList(new Dict("workflow_type",0,"统采流程","类型-统采流程")
            ,new Dict("workflow_type",1,"地材流程","类型-统采流程"));
            return dicts;
        });
    }

}



